import { WebSocketGateway, SubscribeMessage, MessageBody, OnGatewayConnection, OnGatewayDisconnect, WebSocketServer } from '@nestjs/websockets';

import { Server, Socket } from 'socket.io';

@WebSocketGateway()

export class WebSocketGatewayService implements OnGatewayConnection, OnGatewayDisconnect {

  @WebSocketServer() server: Server;

  // 用于管理在线用户
  private users: Map<string, string> = new Map(); // key: userId, value: socketId

  // 连接时触发
  handleConnection(client: Socket) {

    console.log(`Client connected: ${client.id}`);

  }

  // 断开连接时触发
  handleDisconnect(client: Socket) {

    this.users.forEach((userId, socketId) => {

      if (socketId === client.id) {

        this.users.delete(socketId);

        console.log(`Client disconnected: ${userId}`);

      }

    });

  }

  // 监听消息并转发
  @SubscribeMessage('send_message')

  handleMessage(@MessageBody() data: { senderId: string, receiverId: string, message: string }) {

    console.log('Received message:', data);
    // 将消息转发给接收者
    const receiverSocketId = this.users.get(data.receiverId);

    if (receiverSocketId) {

      this.server.to(receiverSocketId).emit('receive_message', data);

    }

  }

  // 监听用户加入
  @SubscribeMessage('join')

  handleJoin(@MessageBody() userId: string, client: Socket) {

    this.users.set(userId, client.id);

    console.log(`${userId} joined with socket ID: ${client.id}`);

  }
  
}
